<template>
  <div class="data-auth-finance">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>模块配置及数据权限配置</h3>
        </div>
      </template>

      <el-alert :title="configDetail.desc" type="warning" show-icon :closable="false" />

      <el-form :model="configForm" label-width="120px" label-position="left" class="mt-4">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="权限名称">
              <el-input v-model="configDetail.title" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限标识">
              <el-input v-model="configDetail.name" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="报销管理员">
              <el-input
                v-model="configForm.conf_1_str"
                placeholder="请选择报销管理员"
                readonly
                @click="selectAdmin(1)"
              >
                <template #append>
                  <el-button @click="clearAdmin(1)">清除</el-button>
                </template>
              </el-input>
              <input type="hidden" v-model="configForm.conf_1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限标识">
              <el-input value="conf_1" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="发票管理员">
              <el-input
                v-model="configForm.conf_2_str"
                placeholder="请选择发票管理员"
                readonly
                @click="selectAdmin(2)"
              >
                <template #append>
                  <el-button @click="clearAdmin(2)">清除</el-button>
                </template>
              </el-input>
              <input type="hidden" v-model="configForm.conf_2" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限标识">
              <el-input value="conf_2" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="回款管理员">
              <el-input
                v-model="configForm.conf_3_str"
                placeholder="请选择回款管理员"
                readonly
                @click="selectAdmin(3)"
              >
                <template #append>
                  <el-button @click="clearAdmin(3)">清除</el-button>
                </template>
              </el-input>
              <input type="hidden" v-model="configForm.conf_3" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限标识">
              <el-input value="conf_3" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="付款管理员">
              <el-input
                v-model="configForm.conf_4_str"
                placeholder="请选择付款管理员"
                readonly
                @click="selectAdmin(4)"
              >
                <template #append>
                  <el-button @click="clearAdmin(4)">清除</el-button>
                </template>
              </el-input>
              <input type="hidden" v-model="configForm.conf_4" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限标识">
              <el-input value="conf_4" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="submitForm">立即提交</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 人员选择对话框 -->
    <el-dialog v-model="adminDialogVisible" title="选择人员" width="600px">
      <el-table
        :data="userList"
        highlight-current-row
        @current-change="handleUserSelect"
        v-loading="userLoading"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="department" label="部门" />
      </el-table>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="adminDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAdminSelect">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import {
    getDataauthList as getDataAuthListApi,
    editDataauth as editDataAuthApi,
  } from '@/api/home/dataauth'
  import { useRoute } from 'vue-router'

  // 数据相关
  const route = useRoute()
  const configDetail = ref({
    id: 0,
    title: '',
    name: '',
    desc: '财务模块使用说明：财务模块主要用于管理公司的财务收支，包括费用报销、发票管理、回款管理、付款管理等。支持财务审批流程、财务统计分析等功能。',
  })
  const configForm = reactive({
    id: 0,
    conf_1: '',
    conf_1_str: '',
    conf_2: '',
    conf_2_str: '',
    conf_3: '',
    conf_3_str: '',
    conf_4: '',
    conf_4_str: '',
  })

  // 人员选择相关
  const adminDialogVisible = ref(false)
  const userList = ref<any[]>([])
  const userLoading = ref(false)
  const currentAdminField = ref('')

  // 获取财务数据权限配置
  const getFinanceConfig = async () => {
    try {
      const response: any = await getDataAuthListApi({
        id: route.query.id || 3,
      })

      if (response.data.code === 0) {
        const data = response.data.data
        configDetail.value = data.detail

        // 设置表单数据
        configForm.id = data.detail.id
        configForm.conf_1 = data.detail.conf_1 || ''
        configForm.conf_1_str = data.detail.conf_1_str || ''
        configForm.conf_2 = data.detail.conf_2 || ''
        configForm.conf_2_str = data.detail.conf_2_str || ''
        configForm.conf_3 = data.detail.conf_3 || ''
        configForm.conf_3_str = data.detail.conf_3_str || ''
        configForm.conf_4 = data.detail.conf_4 || ''
        configForm.conf_4_str = data.detail.conf_4_str || ''
      } else {
        ElMessage.error(response.data.msg || '获取财务数据权限配置失败')
      }
    } catch (error) {
      ElMessage.error('获取财务数据权限配置失败')
    }
  }

  // 获取用户列表（模拟）
  const getUserList = async () => {
    try {
      userLoading.value = true
      // 这里应该调用实际的用户列表接口
      // const response: any = await getUserListApi()

      // 模拟数据
      userList.value = [
        { id: 1, name: '张三', department: '销售部' },
        { id: 2, name: '李四', department: '财务部' },
        { id: 3, name: '王五', department: '人事部' },
        { id: 4, name: '赵六', department: '技术部' },
      ]
    } catch (error) {
      // 模拟数据
      userList.value = [
        { id: 1, name: '张三', department: '销售部' },
        { id: 2, name: '李四', department: '财务部' },
        { id: 3, name: '王五', department: '人事部' },
        { id: 4, name: '赵六', department: '技术部' },
      ]
    } finally {
      userLoading.value = false
    }
  }

  // 选择管理员
  const selectAdmin = (field: number) => {
    currentAdminField.value = `conf_${field}`
    getUserList()
    adminDialogVisible.value = true
  }

  // 清除管理员
  const clearAdmin = (field: number) => {
    const fieldStr = `conf_${field}_str`
    const fieldId = `conf_${field}`

    if (fieldStr in configForm) {
      ;(configForm as any)[fieldStr] = ''
    }
    if (fieldId in configForm) {
      ;(configForm as any)[fieldId] = ''
    }
  }

  // 处理用户选择
  const selectedUser = ref<any>(null)
  const handleUserSelect = (row: any) => {
    selectedUser.value = row
  }

  // 确认管理员选择
  const confirmAdminSelect = () => {
    if (selectedUser.value) {
      const fieldStr = `${currentAdminField.value}_str`
      const fieldId = currentAdminField.value

      if (fieldStr in configForm) {
        ;(configForm as any)[fieldStr] = selectedUser.value.name
      }
      if (fieldId in configForm) {
        ;(configForm as any)[fieldId] = selectedUser.value.id
      }

      adminDialogVisible.value = false
    } else {
      ElMessage.warning('请选择一个用户')
    }
  }

  // 提交表单
  const submitForm = async () => {
    try {
      const response: any = await editDataAuthApi(configForm)

      if (response.data.code === 0) {
        ElMessage.success('保存成功')
      } else {
        ElMessage.error(response.data.msg || '保存失败')
      }
    } catch (error) {
      ElMessage.error('保存失败')
    }
  }

  // 重置表单
  const resetForm = () => {
    getFinanceConfig()
  }

  // 初始化
  onMounted(() => {
    getFinanceConfig()
  })
</script>

<style scoped>
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .mt-4 {
    margin-top: 1rem;
  }
</style>
